package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.FaultCountDto;
import com.hualude.roadsign.dto.RuleGroupDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.List;

public class RuleGroupRepositoryImpl {
    @PersistenceContext
    private EntityManager em;

    public List<RuleGroupDto> getRuleGroup4DT(DTRequestDto dtRequestDto, String orgIds, String content, String time)throws Exception{
        boolean andFlag=false;
        StringBuilder sql= new StringBuilder()
                .append("select r.ruleGroupId,r.ruleGroupType,r.ruleGroupName,r.ruleGroupRemarks,r.ruleDeviceCount,")
                .append("r.ruleCreateTime from tb_rule_group r ");

        StringBuilder sql2=new StringBuilder();
        if(orgIds!=null&&orgIds.length()>0){
            if(!andFlag){
                andFlag=true;
            }else {
                sql2.append(" and ");
            }
            sql2.append(" r.ruleGroupOrgId in (").append(orgIds).append(") ");
        }
        if(content!=null&&content.length()>0){
           if(!andFlag){
               andFlag=true;
           }else {
               sql2.append(" and ");
           }
            sql2.append(" r.ruleGroupRemarks like '%").append(content).append("%' ");
        }
        if(time!=null&&time.length()>0){
            if(!andFlag){
                andFlag=true;
            }else {
                sql2.append(" and ");
            }
            sql2.append(" r.ruleCreateTime like '%").append(time).append("%' ");
        }
        if(sql2.length()!=0) {
            sql.append(" where ");
            sql.append(sql2);
        }
        sql.append(" order by r.ruleGroupId ");
        Query query = em.createNativeQuery(sql.toString());
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(RuleGroupDto.class));

        return query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
    }

    public Integer getRuleGroupCount4DT(DTRequestDto dtRequestDto, String orgIds, String content, String time)throws Exception{
        String sql="select count(*) from tb_rule_group r where  r.ruleGroupRemarks " +
                "like '%"+content+"%' and r.ruleCreateTime like '%"+time+"%' order by r.ruleCreateTime desc ";
        Query query = em.createNativeQuery(sql);
        return Integer.parseInt(query.getSingleResult().toString());
    }

}
